import tkinter as tk
from tkinter import ttk
import json5 as json

root = tk.Tk()
root.title("设置打卡用户")
js_config = None
users = None
is_Mult_Thread = None

def gridWidgets():
    tk.Label(frameEntry, text="用户名").grid(row=0, column=0,)
    usernameEntry.grid(row=0, column=1,)
    tk.Label(frameEntry, text="密码").grid(row=1, column=0,)
    passwordEntry.grid(row=1, column=1,)
    # tk.Label(frameEntry, text="宿舍").grid(row=2, column=0,)
    # DormitorieEntry.grid(row=2, column=1,)
    sb.pack(side=tk.RIGHT,fill=tk.Y)
    sb1.pack(side=tk.BOTTOM,fill=tk.X)
    tree.pack(padx=0, pady=0)
    delbutton.grid(row=0, column=0, padx=3)
    insertbuton.grid(row=0, column=1, padx=3)
    mThread.grid(row=0, column=2, padx=3, pady=3)
    frameEntry.pack(padx=10,pady=10)
    frameTree.pack(padx=10)
    frameButton.pack(padx=10,pady=10)

def loadDict():
    global js_config, users, is_Mult_Thread
    try:
        with open("users.json", 'r') as js_file:
            js_config = json.load(js_file)
            users     = js_config["users"]
            is_Mult_Thread  = js_config["thread"]
            for i in users:
                name, pswd, dorm = i[0], i[1], i[2]
                tree.insert(tk.END, f"user:{name},pass:{pswd},dorm:{dorm}")
    except:
        with open("users.json", 'w') as js_file:
            users = []
            js_config = {"users": users,
                        "thread": False}
            is_Mult_Thread  = js_config["thread"]
            js_string = json.dumps(js_config, sort_keys=True, indent=4, separators=(',', ': '))
            js_file.write(js_string)
    mThreadVar.set(int(is_Mult_Thread))
    
def dicToFile():
    global users, js_config, is_Mult_Thread
    with open("users.json", 'w') as js_file:
        js_config = {"users": users,
                    "thread": is_Mult_Thread}
        is_Mult_Thread  = js_config["thread"]
        js_string = json.dumps(js_config, sort_keys=True, indent=4, separators=(',', ': '))
        js_file.write(js_string)

def freshDict():
    global js_config, users, is_Mult_Thread
    all_str = tree.get(0, tk.END)
    users = []
    for i in all_str:
       user, pswd, dorm =  i.split(",")
       user = user[5:]
       pswd = pswd[5:]
       dorm = dorm[5:]
       users.append([user, pswd, dorm])
    # js_config["users"] = users
    # js_config[""]
    dicToFile()
    print(js_config)

def delete(*args):
    global js_config, users, is_Mult_Thread
    tree.delete(tk.ACTIVE)
    freshDict()

def addTree(*args):
    name = usernameEntry.get()
    pswd = passwordEntry.get()
    dormit = DormitorieEntry.get()
    usernameEntry.delete(0, tk.END)
    passwordEntry.delete(0, tk.END)
    DormitorieEntry.delete(0, tk.END)
    tree.insert(tk.END, f"user:{name},pass:{pswd},dorm:{dormit}")
    freshDict()

def setMThread():
    global is_Mult_Thread
    is_Mult_Thread = bool(mThreadVar.get())
    freshDict()

frameEntry = tk.Frame(root)
frameTree = tk.Frame(root)
frameButton = tk.Frame(root)

usernameEntry = tk.Entry(frameEntry)
passwordEntry = tk.Entry(frameEntry)
DormitorieEntry = tk.Entry(frameEntry)

sb = tk.Scrollbar(frameTree)
sb1 = tk.Scrollbar(frameTree, orient=tk.HORIZONTAL)
tree = tk.Listbox(frameTree, width=30, xscrollcommand=sb1.set, yscrollcommand=sb.set)
sb.config(command=tree.yview)
sb1.config(command=tree.xview)


delbutton = tk.Button(frameButton, text="删除", command=delete)
root.bind("<Delete>", delete)
insertbuton = tk.Button(frameButton,text="插入",command=addTree)
root.bind("<Return>", addTree)
mThreadVar = tk.IntVar()
mThread = tk.Checkbutton(frameButton,text="多线程", command=setMThread, variable=mThreadVar)


def main():
    loadDict()
    gridWidgets()
    root.mainloop()

if __name__ == "__main__":
    main()